package cn.jy.careuplusdoctor.injector;

import java.lang.reflect.Field;



import android.app.Activity;
import android.view.View;

public class InjectorUitls {

	private static InjectorUitls instance;
	
	private InjectorUitls(){}
	
	public static InjectorUitls getInstance()
	{
		if (instance == null) {
			instance = new InjectorUitls();
		}
		return instance;
	}
	
	public void injectAllView(Activity activity)
	{
		Field[] fields = activity.getClass().getDeclaredFields();
		if (fields !=null && fields.length >0) {
			for (Field field : fields) {
				if (field.isAnnotationPresent(IdInject.class)) {
					IdInject id = field.getAnnotation(IdInject.class);
					if (id.id() == -1)
						continue;
					injectView(activity,field);
				}
			}
		}
	}
	
	public void injectView(Activity activity,Field field)
	{
		if (field.isAnnotationPresent(IdInject.class)) {
			IdInject inject = field.getAnnotation(IdInject.class);
			
			if (inject.id() == -1)
				return;
			field.setAccessible(true);
			View view = activity.findViewById(inject.id());
			try {
				field.set(activity, view);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
		}
	}
	
	
	
	public void injectFromView(Object obj,View view)
	{
		Field[] fields = obj.getClass().getDeclaredFields();
		if (fields !=null && fields.length >0) {
			for (Field field : fields) {
				injectView(obj,view,field);
			}
		}
	}
	
	public void injectView(Object obj,View view,Field field)
	{
		if (field.isAnnotationPresent(IdInject.class)) {
			IdInject inject = field.getAnnotation(IdInject.class);
			int id = inject.id();
			if (id == -1) 
				return;
			field.setAccessible(true);
			View childView = view.findViewById(id);
			try {
				field.set(obj, childView);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				return;
			}
		}
	}
}
